-module(server).

-export([
    listen/1
]).

-define(TCP_OPTIONS, [binary, {packet, 0}, {active, false}, {reuseaddr, true}]).

% Call echo:listen(Port) to start the service.
listen(Port) ->
    {ok, LSocket} = gen_tcp:listen(Port, ?TCP_OPTIONS),
    accept(LSocket).

% Wait for incoming connections and spawn the echo loop when we get one.
accept(LSocket) ->
    {ok, Socket} = gen_tcp:accept(LSocket),
    spawn(fun() ->
        gen_tcp:send(Socket, "Input test file name: "),
        case gen_tcp:recv(Socket, 0) of
            {ok, Value} ->
                StrValue = io_lib:format("~s",[Value]),
                [InValue] = StrValue,
                Len = string:len(InValue),
                gen_tcp:send(Socket, io_lib:format("Len: ~w~n",[Len])),
                StripValue = string:left(InValue,Len-1),
                %tell opening
                gen_tcp:send(Socket, io_lib:format("Opening file: ~s~n",[StripValue])),

                %spawn interpreter
                Interpreter = spawn(interpreter,interpret,[Socket]),

                %spawn parser
                Parser = spawn(parser,parse,[Interpreter]),

                %read!
                reader:readFile(StripValue,Parser);
            _ ->
                %loop
                self()
        end
    end),
    accept(LSocket).